package com.gds.wiki.cloud.memberCenter.server.security.oauth2.core.authenticator;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gds.wiki.cloud.framework.common.exception.BizExceptionEnum;
import com.gds.wiki.cloud.framework.common.exception.BusinessException;
import com.gds.wiki.cloud.memberCenter.client.member.model.Member;
import com.gds.wiki.cloud.memberCenter.server.modular.member.service.MemberService;
import com.gds.wiki.cloud.oauth2.common.integration.IntegrationAuthentication;
import com.gds.wiki.cloud.oauth2.common.integration.authenticator.AbstractPreparableIntegrationAuthenticator;
import com.gds.wiki.cloud.oauth2.common.model.SecurityMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


/**
 * 默认登录处理
 * @author WIKI
 * @date 2018-3-31
 **/
@Component
@Primary
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    private MemberService memberService;


    @Override
    public SecurityMember authenticate(IntegrationAuthentication integrationAuthentication){
        String username=integrationAuthentication.getAuthParameter("username");
        String password=integrationAuthentication.getAuthParameter("password");
        if(StrUtil.isEmpty(username)){
            throw new BusinessException(BizExceptionEnum.LOGIN_USERNAME_ERROR);
        }
        if(StrUtil.isEmpty(password)){
            throw new BusinessException(BizExceptionEnum.LOGIN_PASSWORD_NULL);
        }

            Wrapper<Member> queryWrapper=new QueryWrapper<>();
            ((QueryWrapper<Member>) queryWrapper).ge("name",integrationAuthentication.getUsername());
            Member  member = memberService.getOne(queryWrapper);
            if(member==null){
                throw new BusinessException(BizExceptionEnum.NO_THIS_USER);
            }


            SecurityMember securityMember=new SecurityMember(member.getLoginName(),member.getPassWord());
            securityMember.setId(member.getId());
            return securityMember;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) throws BusinessException {


    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.isEmpty(integrationAuthentication.getAuthType());
    }
}
